package com.example.security;


import cn.hutool.json.JSONUtil;
import com.example.common.lang.Result;
import com.example.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户退出处理器
 */
@Component
public class JwtLogoutSuccessHandler implements LogoutSuccessHandler {

    @Autowired
    JwtUtils jwtUtils;                                              //把JwtUtils注入ioc容器

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        if(authentication != null) {            //判断authentication不为空则，调用security内置退出处理器
            new SecurityContextLogoutHandler().logout(request,response,authentication);
        }

        response.setContentType("application/json;charset=UTF-8");  //返回数据为json格式，utf-8编码
        ServletOutputStream outputStream = response.getOutputStream();  //生成输出流准备用输出流的方式flush推出


        response.setHeader(jwtUtils.getHeader(),"");          //清空请求头中jwt的值

        Result result = Result.succ("????");              //成功返回的结果

        outputStream.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));    //把Result序列化成json的字节码utf-8格式

        outputStream.flush();       //把流推出
        outputStream.close();       //释放资源
    }
}
